*******************************************************************************
* Open data
*******************************************************************************

use dataset_polls, clear

*******************************************************************************
* Set time periods to iterate over
*******************************************************************************

format date %dm_Y

local c2000a = date("11-07-2000", "MDY")
local c2000b = date("12-12-2000", "MDY")
local c2000c = date("11-02-2004", "MDY")
local c2016 = date("11-08-2016", "MDY")
local c2020 = date("11-03-2020", "MDY")

*******************************************************************************
* Do the regressions for each cycle
*******************************************************************************

eststo clear

forvalues i = 1(1)3 {

preserve

	if `i' == 1 {
		gen x = date - `c2000b'
		local c2000c = `c2000c' - `c2000b'
		keep if year(date) < 2005
	}	
	if `i' == 2 {
		keep if year(date) > 2005 & year(date) < 2020
		gen x = date - `c2016'
	}
	if `i' == 3 {
		keep if year(date) > 2019
		gen x = date - `c2020'
	}
	
	keep if x > 0
	su x
	replace x = (x - r(min)) / (r(max) - r(min))
	
	rename x Time
	eststo, title("Dem"): reg legitimatec Time if regex(subs, "Dem")
	eststo, title("Rep"): reg legitimatec Time if regex(subs, "Rep")
	
restore

}

*******************************************************************************
* Output table
*******************************************************************************

#delimit;

esttab
	using "_output/table_appendix_trends_regression.tex"
	,
		replace
		booktabs
		label
		collabels(none)
		cells(b(fmt(3) star) se(par))
		width(\linewidth)
		compress
		gap
		alignment(l)
		mtitles
		mgroups(
			"2000" "2016" "2020", 
			pattern(1 0 1 0 1 0)
			prefix(\multicolumn{@span}{c}{) suffix(}) 
			span 
		)		
		;
			
#delimit cr	

*******************************************************************************
* End
*******************************************************************************
